import React, { Component } from 'react'
import './userLogin.scss'
import {connect} from 'react-redux'
import axios from 'axios'
import {Toast} from 'antd-mobile'

function showToast(value) {
  Toast.info(value, 1);
}

function successToast(value) {
  Toast.success(value, 1);
}


 class UserLogin extends Component {
  constructor(){
    super()
    this.state={
      password:''
    }
  }
  
  render() {
    return (
      <div id='loginWap'>
        <div className='loginBox'>
          <div className='loginbox1'><img src='//yanxuan.nosdn.127.net/39c5e4583753d4c3cb868a64c2c109ea.png' alt=''></img></div>
          <div className='loginbox2'>
            <p className='telBox border-bottom'><input placeholder='用户账号' value={this.props.username} onChange={(e)=>{this.props.changeUser(e.target.value)}}/></p>
            <p  className='telBox1 border-bottom'><input type='password'  placeholder='密码' className='userInputLogin' value={this.state.password} onChange={(e) =>{this.setState({password:e.target.value})}}/></p>
            <p className='telBox2'><span onClick={() =>{this.props.history.push('/login/register')}}>注册账号</span><span onClick={() =>{this.props.history.push('/login/changeLogin')}}>忘记密码</span></p>
            <p className='loginButton' onClick={()=>{this.change(this.props.username)}}>登录</p>
            <p className='hisLogin'><span onClick={() =>{this.props.history.push('/login')}}>其他登录方式</span></p>
          </div>
        </div>
      </div>
    )
  }

  change=(username)=>{
    axios.post('http://10.36.149.139:9000/api/user/login',{
      username,
      type:'password',
      value: this.state.password
    }).then(({data}) =>{
      if(data.code === -1){
        showToast(data.message)
        return
      }
      successToast(data.message)
      this.props.saveState(data)
      localStorage.setItem('loginId',JSON.stringify(data))
      this.props.history.push('/')
    })
  }
}

const mapStateToProps=(state) =>{
  return{
    username:state.getIn(['userReducer','userInfo','userName'])
  }
}

const mapActionToProps=(dispatch)=>{
  return{
    changeUser(value){
      dispatch({
        type:'changeUser',
        value
      })
    },
    saveState(value){
      dispatch({
        type:'saveState',
        value
      })
    }
  }
}


export default connect(mapStateToProps,mapActionToProps)(UserLogin)
